<?php

namespace app\admin\model;

use app\api\model\UserCoupon;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

class Coupon extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'coupon';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'end_time_text',
        'type_text'
    ];
    


    
    public function getTypeList()
    {
        return ['discount' => '折扣','reward'=>'满减','goods'=>'赠品'];
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function goods()
    {
        return $this->belongsTo('app\\admin\\model\\shop\\Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * Notes:领取优惠券
     * User: gai
     * Date: 2023/3/30
     * Time: 15:34
     */
    public function receiveCoupon($coupon_id,$user_id,$get_type,$is_stock=0,$is_limit = 1){
        $coupon_type_info = Coupon::get($coupon_id);
        if (!empty($coupon_type_info)) {

            if ($coupon_type_info['count'] != -1 || $is_stock == 0) {
                if ($coupon_type_info['count'] == $coupon_type_info['lead_count']) {
                    throw new Exception('来迟了该优惠券已被领取完了');
                }
            }

            if ($coupon_type_info['max_fetch'] != 0) {
                //限制领取
                $member_receive_num = UserCoupon::where(['coupon_id'=>$coupon_id,'user_id'=>$user_id])->count();

                if ($member_receive_num >= $coupon_type_info['max_fetch'] && $is_limit == 1) {
                    throw new Exception('该优惠券领取已达到上限');
                }
            }

            //只有正在进行中的优惠券可以添加或者发送领取)
            if ($coupon_type_info['status'] != 1) {
                throw new Exception('该优惠券已过期');
            }
            $user_coupon = new UserCoupon();
            $user_coupon->setAttr('type',$coupon_type_info->getAttr('type'));
            $user_coupon->user_id = $user_id;
            $user_coupon->coupon_id = $coupon_id;
            $user_coupon->coupon_name = $coupon_type_info->coupon_name;
            $user_coupon->at_least = $coupon_type_info->at_least;
            $user_coupon->money = $coupon_type_info->money;
            $user_coupon->discount = $coupon_type_info->discount;
            $user_coupon->discount_limit = $coupon_type_info->discount_limit;
            $user_coupon->goods_id = $coupon_type_info->goods_id;
            $user_coupon->get_type = $get_type;
            $user_coupon->state = 1;
            $user_coupon->start_time = time();
            if ($coupon_type_info->validity_type==1){
                $user_coupon->end_time = time()+$coupon_type_info->fixed_term*86400;
            } else {
                $user_coupon->end_time = $coupon_type_info->end_time;
            }

            $res = $user_coupon->save();

            if ($res){
                if ($is_stock == 0) {
                    Coupon::where(['id'=>$coupon_id])->setInc('lead_count',1);
                }
                return  $res;

            } else {
                throw new Exception('领取失败');
            }

        } else {
            throw new Exception('未查找到该优惠券');
        }
    }


    /**
     * Notes:处理过期的优惠券
     * User: gai
     * Date: 2023/11/4
     * Time: 14:55
     */
    public static function expiration($id)
    {
        $res = Coupon::where('id',$id)->update(['status'=>2]);
        return $res;
    }


    /**
     * Notes:处理用户过期的优惠券
     * User: gai
     * Date: 2023/11/4
     * Time: 14:55
     */
    public static function user_expiration()
    {
        $res = UserCoupon::where('state',1)->where('end_time', '<=', time())->update(['state'=>3]);
        return $res;
    }

}
